package com.dong.auth.security.authentication;

import com.dong.auth.security.exception.AuthenticationException;

import java.util.Collections;
import java.util.List;

/**
 * ProviderManager is the most commonly used implementation of AuthenticationManager.
 *
 * @author zhaodongchao
 * @version V1.0
 * @date 2021/10/19 1:27
 */
public class ProviderManager implements AuthenticationManager {
    private List<AuthenticationProvider> providers ;

    public ProviderManager(List<AuthenticationProvider> providers) {
        this.providers = providers;
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        for (AuthenticationProvider provider : this.providers) {
            if (!provider.supports(authentication.getClass())) {
                continue;
            }
            return provider.authenticate(authentication);
        }
        //如果没有合适的AuthenticationProvider实现去提供认证服务，就抛出异常
        throw new AuthenticationException("没有合适的AuthenticationProvider提供认证服务！");
    }

    public List<AuthenticationProvider> getProviders() {
        return providers;
    }
}
